package cn.com.hhrcw.job;

import cn.com.hhrcw.conferenceRoom.entity.ConferenceRoom;
import cn.com.hhrcw.conferenceRoom.service.IConferenceRoomService;
import cn.com.hhrcw.utils.RedisLockUtils;
import cn.hutool.core.date.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

/**
 * @ProjectName: recruit-boot-parent
 * @Package: cn.com.hhrcw.job
 * @ClassName: InterviewTask
 * @Author: 朱修轩
 * @Description: 视频面试定时任务 创建面试房间
 * @Date: 2021/5/20 16:04
 * @Version: 1.0
 */
@Component("InterviewTask")
@Slf4j
public class InterviewTask implements Job {
    @Autowired
    private IConferenceRoomService conferenceRoomService;


    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        try {
            if (RedisLockUtils.tryLock("INTERVIEW_TASK", 120)) {
                List<ConferenceRoom> list = conferenceRoomService.lambdaQuery().eq(ConferenceRoom::getDelFlag, 0)
                    //结束时间小于当前时间
                    .le(ConferenceRoom::getEffectiveEndTime, DateUtil.format(new Date(), "yyyy-MM-dd HH:mm"))
                    .eq(ConferenceRoom::getStatus, 1).list();
                for (ConferenceRoom conferenceRoom : list) {
                    try {
                        conferenceRoom.setEffectiveBeginTime(DateUtil.offsetHour(new Date(), 1));
                        conferenceRoomService.createMeeting(conferenceRoom);
                    } catch (Exception e) {
                        log.info("会议室创建失败-----"+conferenceRoom.getRoomName());
                    }
                }
            }
        } finally {
            RedisLockUtils.unLock("INTERVIEW_START_TASK");
        }

//        Set<Object> range = redisUtil.zRange("createMeeting", 0, 0);
//        Object[] objects = range.toArray();
//        if(objects.length > 0){
//            Object id = objects[0];
//            //防重复执行
//            if (redisTemplate.hasKey("createMeeting"+ id +"_locked")) {
//                log.warn("创建" + id + "任务执行中...");
//                return;
//            }
//            if (RedisLockUtils.tryLock("createMeeting" + id, 120)) {
//                String meetingId = ""; // 会议室id
//                try {
//                    DateTime date = DateUtil.date();
//                    Double time = redisUtil.zScore("createMeeting", id);
//                    // 判断会议室是否开始 提前10分钟创建会议室
//                    DateTime startTime = DateUtil.offsetMinute(DateUtil.date(time.longValue()),-10);
//                    log.info("-------------------------开始创建时间"+DateUtil.format(startTime,"yyyy-MM-dd HH:mm:ss") + "当前时间"+DateUtil.format(date,"yyyy-MM-dd HH:mm:ss"));
//
//                    if (DateUtil.compare(date,startTime) >= 0){
//                        // 创建会议室
//                        OpInterviewHistory opInterviewHistory = opInterviewHistoryService.getById(id.toString());
//                        CreateMeetingParam createMeetingParam = new CreateMeetingParam();
//                        DateTime dateTime = DateUtil.offsetHour(opInterviewHistory.getTime(), -8);
//                        createMeetingParam.setStartTime(DateUtil.format(dateTime,"yyyy-MM-dd HH:mm"));
//
//                        Date interviewStartTime = opInterviewHistory.getTime();
//                        Date interviewEndTime = opInterviewHistory.getInterviewEndTime();
//                        long between = DateUtil.between(interviewEndTime, interviewStartTime, DateUnit.MINUTE);
//                        createMeetingParam.setLength(between);
//                        String userId = opInterviewHistory.getUserId();
//                        PiInfo byId = piInfoService.getById(userId);
//                        createMeetingParam.setSubject(byId.getName() + "的视频面试");
//                        createMeetingParam.setMediaTypes("HDVideo");
//                        createMeetingParam.setVmrFlag(1);
//                        JSONArray jsonArray = huaWeiRoomService.meetingList();
//                                // 取出未占用的会议室
//                        List<JSONObject> jsonObjects = jsonArray.toJavaList(JSONObject.class);
////                        for (JSONObject jsonObject : jsonObjects) {
////                            meetingId = jsonObject.getString("id");
////                            boolean hasKey = redisUtil.hasKey("inuseMeeting:" + meetingId);
////                            if(!hasKey){
////                                redisUtil.set("inuseMeeting:" + meetingId, true); // 设置会议室占用
////                                break;
////                            }
////                        }
//
//                        for (JSONObject json : jsonObjects) {
//                            String mId = json.getString("id");
//                            boolean hasKey = redisUtil.hasKey("inuseMeeting:" + mId);
//                            if(!hasKey){
//                                meetingId = mId;
//                                break;
//                            }
//                        }
//                        if(StringUtils.isNotBlank(meetingId)){
//                            createMeetingParam.setVmrID(meetingId);
//                            redisUtil.set("inuseMeeting:" + meetingId, true); // 设置会议室占用
//                        }else{
//                            log.info("-------------------没有空闲的会议室---------------------------");
//                            throw new Exception("没有空闲的会议室");
//                        }
//                        redisUtil.zRemove("createMeeting", id); // 释放创建会议室
//                        JSONObject meeting = huaWeiRoomService.createMeeting(createMeetingParam);
//                        if(null != meeting){
//                            opInterviewHistoryService.lambdaUpdate().set(OpInterviewHistory::getR1, meeting.getString("chairJoinUri"))
//                                    .set(OpInterviewHistory::getR2, meetingId)
//                                    .set(OpInterviewHistory::getR3, meeting.getString("conferenceID"))
//                                    .set(OpInterviewHistory::getInternetUrl, meeting.getString("guestJoinUri"))
//                                    .eq(OpInterviewHistory::getId, opInterviewHistory.getId()).update();
//
//                            // 加入关闭会议室队列
//                            redisUtil.zSet("closeMeeting",opInterviewHistory.getId(),opInterviewHistory.getInterviewEndTime().getTime());
//                        }
//                    }
//                }catch (Exception e){
//                    log.error("创建面试房间错误" + e.getMessage(), e);
//                }finally {
//                    RedisLockUtils.unLock("createMeeting" + id);
//                }
//
//            }
//        }

    }
}
